<template>
  <div class="recommend-section">
    <h2>为你推荐</h2>
    <van-pull-refresh v-model="state.isRefresh" @refresh="onRefresh">
      <van-list
          v-model:loading="state.isLoading"
          :finished="state.finished"
          finished-text="没有更多了"
          @load="onLoad"
      >
        <div class="recommend-grid">
          <div v-for="item in recommendList" :key="item.gameId" class="game-card" @click="goDetail(item.gameId)">
            <!-- 左侧大图 -->
            <div class="game-image-wrapper">
              <img :src="item.coverImage" alt="" class="game-image" />
            </div>
            <!-- 右侧文字信息 -->
            <div class="game-info">
              <p class="title">{{ item.gameName }}</p>
              <p class="tag">大家都在玩</p>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive,onMounted } from 'vue'
import axios from '@/utils/axios.ts'
import { useRouter } from 'vue-router'

// 定义游戏数据接口
interface Game {
  gameId: number
  gameName: string
  coverImage: string
  platform?: string
  type?: string
  score?: number
}

const recommendList = ref<Game[]>([])
const router = useRouter()

// 控制状态
const state = reactive({
  isRefresh: false,
  isLoading: false,
  finished: false,
})

// 分页参数
const data = reactive({
  page: 1,
  limit: 10,
  refreshKey: 0, // 用于标识刷新次数
})

// 跳转到游戏详情页
const goDetail = (gameId: number) => {
  if (!gameId) {
    console.warn('游戏ID无效，跳转取消')
    return
  }
  router.push({ name: 'goGameDetail', params: { id: gameId } })
}

// 加载更多游戏
const onLoad = () => {
  // 如果是刷新状态，不执行加载更多
  if (state.isRefresh) {
    state.isLoading = false
    return
  }
  
  state.isLoading = true
  
  // 添加刷新键参数确保获取新的推荐内容
  axios.get(`/api/games/recommend?page=${data.page}&limit=${data.limit}&refreshKey=${data.refreshKey}`)
      .then(res => {
        const records = res.data.records || []
        if (records.length === 0) {
          state.finished = true
        } else {
          if (data.page === 1) {
            recommendList.value = records.map((item: any) => ({
              gameId: item.gameId,
              gameName: item.gameName,
              coverImage: item.coverImage,
              platform: item.platform,
              type: item.type,
              score: item.score
            }))
          } else {
            recommendList.value = [...recommendList.value, ...records.map((item: any) => ({
              gameId: item.gameId,
              gameName: item.gameName,
              coverImage: item.coverImage,
              platform: item.platform,
              type: item.type,
              score: item.score
            }))]
          }
          data.page++
        }
        state.isLoading = false
      })
      .catch(err => {
        console.error('推荐加载失败:', err)
        state.isLoading = false
      })
}

// 下拉刷新 - 获取新的推荐内容
const onRefresh = () => {
  state.isRefresh = true
  state.finished = false
  data.page = 1
  data.refreshKey++ // 增加刷新键，确保获取新的推荐内容
  
  axios.get(`/api/games/recommend?page=${data.page}&limit=${data.limit}&refreshKey=${data.refreshKey}`)
      .then(res => {
        const records = res.data.records || []
        recommendList.value = records.map((item: any) => ({
          gameId: item.gameId,
          gameName: item.gameName,
          coverImage: item.coverImage,
          platform: item.platform,
          type: item.type,
          score: item.score
        }))
        data.page = 2 // 下次加载从第二页开始
        state.isRefresh = false
      })
      .catch(err => {
        console.error('刷新失败:', err)
        state.isRefresh = false
      })
}

// 页面挂载时初始化
onMounted(() => {
  onLoad()
})
</script>

<style scoped>
.recommend-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  padding: 16px;
}

.game-card {
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: transform 0.2s;
  height: 200px;
  display: flex;
  align-items: center;
  position: relative;
}

.game-image-wrapper {
  width: 200px;
  height: 150px;
  margin-right: 16px;
  overflow: hidden;
  border-radius: 8px;
}

.game-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.game-info {
  flex: 1;
  padding: 8px 0;
}

.title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
  color: #333;
}

.tag {
  font-size: 12px;
  color: #999;
}
</style>